package com.gmall.security.filter;

import com.alibaba.fastjson.JSON;
import com.gmall.common.model.Response;
import com.gmall.common.util.JwtUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author HL.Wu
 * @date 2020/5/25 17:32
 * Copyright ©https://blog.csdn.net/qq_31150503 Copyright@2009-2020 AII Right Reserve
 */
public class CoreAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 设置编码格式
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setHeader("Access-Control-Allow-Credentials", "false");
        response.setHeader("Access-Control-Expose-Headers", JwtUtil.TOKEN_HEADER);
        Response resp = CoreAuthFilter.authExceptionHandle(authException);
        response.getWriter().write(JSON.toJSONString(resp));
    }
}
